﻿using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AnyTap.Models;
using View = Android.Views.View;
namespace AnyTap;

/// <summary>
/// 全局浮动小球
/// https://www.bbsmax.com/A/Gkz1N27NJR/
/// https://codeload.github.com/Arlenxiao/Xamarin-Example/zip/refs/heads/master
/// </summary>
[Service]
public class BallService : Service, View.IOnTouchListener
{
	private LinearLayout layout = null;
	private IScheduler scheduler = null;

	private IWindowManager WindowManager => GetSystemService(WindowService).JavaCast<IWindowManager>(); //不是简单的类型转换，一定要用 JavaCast

	public BallService()
	{ }

	public override IBinder OnBind(Intent intent) => null;

	public override void OnCreate()
	{
		base.OnCreate();
		scheduler = App.Current as IScheduler;
		layout = new LinearLayout(this);
		layout.SetOnTouchListener(this);

		var image = new ImageView(this);
		image.SetImageResource(Resource.Drawable.menu);
		layout.AddView(image);

		var start = new Android.Widget.Button(this) { Text = "启动" };
		start.Click += (s, e) => scheduler?.Start();
		layout.AddView(start);

		var pause = new Android.Widget.Switch(this) { Text = "暂停" };
		pause.Click += (s, e) => scheduler?.Pause(pause.Checked);
		layout.AddView(pause);

		var goback = new Android.Widget.Button(this) { Text = "返回" };
		goback.Click += (s, e) =>
		{
			StopSelf();
			scheduler?.Stop();
			Android.App.Application.Context.StartActivity(Android.App.Application.Context.PackageManager.GetLaunchIntentForPackage(Android.App.Application.Context.PackageName).SetFlags(ActivityFlags.NewTask));
		};
		layout.AddView(goback);

		WindowManager.AddView(layout, new WindowManagerLayoutParams
		{
			X = 12,
			Y = 12,
			Width = ViewGroup.LayoutParams.WrapContent,
			Height = ViewGroup.LayoutParams.WrapContent,
			Gravity = GravityFlags.Bottom | GravityFlags.Center,
			Flags = WindowManagerFlags.NotFocusable,
			Type = OperatingSystem.IsAndroidVersionAtLeast(26) ? WindowManagerTypes.ApplicationOverlay : WindowManagerTypes.Phone, //必须设置,不然会在 WindowManager.AddView 的时候报错
			Format = Android.Graphics.Format.Transparent
		});
	}

	public override void OnDestroy()
	{
		base.OnDestroy();
		WindowManager.RemoveView(layout);
	}

	protected override void Dispose(bool disposing)
	{
		base.Dispose(disposing);
		if(disposing && layout != null)
		{
			layout.Dispose();
		}
	}

	public bool OnTouch(View v, MotionEvent e)
	{
		if(v.LayoutParameters is WindowManagerLayoutParams parm && e.Action == MotionEventActions.Up)
		{
			parm.X += (int)e.GetX() - v.MeasuredHeight / 2;
			parm.Y -= (int)e.GetY() - v.MeasuredHeight / 2;
			WindowManager.UpdateViewLayout(v, parm);
		}
		return false; //1.返回值是 true,执行完一个动作以后不会结束本次事件的监听，而是继续监听本次事件余下的动作; 2.返回值是 false，执行完一个动作以后结束本次事件的监听，不会在监听余下的动作，等待下一次触摸事件的到来
	}
}
